package com.ruoyi.order.print;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.dto.ShortSearchBody;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.PachongTool;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.vo.OrderVO;
import com.ruoyi.order.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@Service("print")
@Slf4j
public class PrintServiceImpl implements OrderService {

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public List<OrderVO> fetchData(ShortSearchBody shortSearchBody){
         String result =PachongTool.getDataShort(shortSearchBody.getCookie(),shortSearchBody.getBegin(),shortSearchBody.getEnd(),
                 shortSearchBody.getPage(),shortSearchBody.getPageSize(),shortSearchBody.getCustomStatus());
         List<OrderVO> orderVOList = Lists.newArrayList();
        if (StringUtils.isNotEmpty(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String code = jsonObject.getString("code");
            String message = jsonObject.getString("message");
            if ("20000".equals(code)) {
                JSONObject data = jsonObject.getJSONObject("data");
                JSONArray records = data.getJSONArray("records");
                CountDownLatch latch = new CountDownLatch(records.size());
                for (int i = 0; i < records.size(); i++) {
                    JSONObject record = records.getJSONObject(i);
                    Long createTime = record.getLong("createTime");
                    String itemTitle = record.getString("itemTitle");
                    BigDecimal price = record.getBigDecimal("price").divide(new BigDecimal(100), RoundingMode.DOWN);
                    String realName = record.getString("consignee");
                    String phone = record.getString("mobile");
                    String province = record.getString("province");
                    String city = record.getString("city");
                    String district = record.getString("district");
                    String address = record.getString("address");
                    String orderId = record.getString("id");
                    String expressNo = record.getString("trackingNo");
                    OrderVO vo = new OrderVO();
                    vo.setAddress(province.equals(city)?"":province+city+district+address);
                    vo.setExpressNo(expressNo);
                    vo.setOrderNo(orderId);
                    vo.setOrderDate(new Date(createTime));
                    vo.setPhone(phone);
                    vo.setRealName(realName);
                    vo.setProductName(itemTitle);
                    vo.setPrice(price);
                    // 多线程 查询单号所属快递公司和入库

                        threadPoolTaskExecutor.execute(()->{
                            try{
                            String expressName = PachongTool.getExpressName(expressNo);
                            vo.setExpressCompany(expressName);
                            // 入库 TODO
                            } catch (Exception e){
                                log.error("爬虫失败:{}",e.getMessage(),e);
                            }finally {
                                latch.countDown();
                            }
                        });

                    orderVOList.add(vo);
                }
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    log.error("爬虫失败多线程异常:{}",e.getMessage(),e);
                }
            } else {
                throw new ServiceException(message);
            }
        }
        return orderVOList;
    }
}
